package pl.pawluk.inz.security.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import pl.pawluk.inz.dao.IUsersService;
import pl.pawluk.inz.exceptions.ErrorCodes;
import pl.pawluk.inz.exceptions.VLPException;

/*
 * Spring-security requires an implementation of UserDetailService. 
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Log log = LogFactory.getLog(UserDetailsServiceImpl.class);
    @Autowired
    private IUsersService usersService;

    /*
      * Mock for users from database.
      * In the real application users will be retrieved from database and
      * proper Spring UserDetails object will be created then for each database user.
      */

    @Override
    public UserDetails loadUserByUsername(String username) {
        log.info("Rozpoczynam odczyt użytkownika: " + username);

        User user = usersService.findByName(username);

        if (user == null) {
            throw new VLPException(ErrorCodes.BLAD_LOGOWANIA);
        }

        log.info("Użytkownik rozpoznany: " + username);
        return user;
    }

}
